package cn.nawang.ebeim.server.transfer;

import cn.nawang.ebeim.server.constants.Config;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.traffic.ChannelTrafficShapingHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

public class TransferServer implements Runnable {

    private static final Logger LOG = LoggerFactory.getLogger(TransferServer.class);

    /**
     * 链路心跳频率
     */
    private static final int HEARTBEAT = 10;

    public void start(int port) throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        public void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new HttpServerCodec())
                                    .addLast(new ChunkedWriteHandler())
                                    .addLast(new LineBasedFrameDecoder(1024))
                                    .addLast(new ChannelTrafficShapingHandler(
                                            Config.WRITE_LIMIT, Config.READ_LIMIT, Config.CHECK_INTERVAL))
                                    .addLast(new IdleStateHandler(HEARTBEAT, HEARTBEAT, 0, TimeUnit.SECONDS))
                                    .addLast(new TransferServerHandler());
                        }
                    }).option(ChannelOption.SO_BACKLOG, 64);
            ChannelFuture f = b.bind(port).sync();
            LOG.info("server start up ==> http://{}:{}/",Config.UPLOAD_HOST, port);
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }

    public void run() {
        try {
            start(Config.UPLOAD_PORT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
